package com.fsp.demoStreamFilter02;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fushengping
 * @className MockStream
 * @description
 * @date 2021/12/1 10:30
 */
public class MockStream {
    public static void main(String[] args) throws JsonProcessingException {
        MyList<Person> personMyList = new MyList<>();
        personMyList.add(new Person("李健",46));
        personMyList.add(new Person("周深",28));
        personMyList.add(new Person("张学友",56));

        //使用自定义filter进行过滤
        // 过渡1：把Lambda赋值给变量，然后在传递
        Predicate<Person> predicate1 = person -> person.getAge() > 40;
        List<Person> filteredList1 = personMyList.filter(predicate1);
        prettyPrint(filteredList1);
        System.out.println("\n---------------------------------------------\n");

        // 不像Stream API？这样写呢？
        /*filter方法的参数中，用一个接口占了坑，这个接口的坑可以使用lambda表达式*/
        List<Person> filteredList2 = personMyList.filter(person -> person.getAge() < 40);
        prettyPrint(filteredList2);
        System.out.println("\n---------------------------------------------\n");

        /*有请真正的Stream API（要用真的List了，不能用山寨MyList）*/
        List<Person> list = new ArrayList<>();
        list.add(new Person("李健",46));
        list.add(new Person("周深",28));
        list.add(new Person("张学友",56));
        List<Person> filteredList3 = list.stream().filter(person -> person.getAge() > 40).collect(Collectors.toList());
        prettyPrint(filteredList3);
    }

    /**
     * 按JSON格式输出
     *
     * @param obj
     * @throws JsonProcessingException
     */
    private static void prettyPrint(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        System.out.println(s);
    }

}
